package cn.easy.rest.controller;

import cn.easy.api.DeviceService;
import cn.easy.common.pojo.EasyResult;
import cn.easy.common.util.CheckNumberUtil;
import cn.easy.common.util.ExceptionUtil;
import cn.easy.pojo.Device;
import cn.easy.pojo.User;
import cn.easy.rest.dao.JedisClient;
import cn.easy.rest.util.UserKeyUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.fasterxml.jackson.databind.ObjectMapper;
import jdk.nashorn.internal.runtime.linker.InvokeByName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.EscapedErrors;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * 设备
 *
 * @author 谢子豪
 * @time 2017/10/4
 * @description
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/device")
@Controller
public class DeviceController {
    @Reference
    private DeviceService deviceService;
    @Autowired
    private JedisClient jedisClient;

    /**
     * 新增一个设备
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    @ResponseBody
    public EasyResult insertDevice(@RequestBody Map map, HttpServletRequest request) {
        String userKey = UserKeyUtil.getUserInfoFromToken(request, jedisClient);
        if (userKey == null) {
            return EasyResult.fail("用户key不能为空");
        }
        //拿出需要的内容
        Device device = new Device();
        //设备名
        if (map.containsKey("name")) device.setDeviceName(map.get("name").toString());
        else return EasyResult.fail("设备名不能为空");
        //描述
        if (map.containsKey("desc")) device.setDeviceDesc(map.get("desc").toString());
        //经纬度
        if (map.containsKey("longitude") && map.containsKey("latitude")) {
            if (CheckNumberUtil.isNumeric(map.get("longitude").toString()))
                device.setDeviceLongitude(map.get("longitude").toString());
            if (CheckNumberUtil.isNumeric(map.get("latitude").toString()))
                device.setDeviceLatitude(map.get("latitude").toString());
        }
        //标签
        if (map.containsKey("tag")) device.setDeviceTag(map.get("tag").toString());
        //是否为私人
        if (map.containsKey("personal")) {
            if (CheckNumberUtil.isNumeric(map.get("personal").toString())) {
                int personal = Integer.parseInt(map.get("personal").toString());
                if (personal == 1 || personal == 0) device.setDevicePersonal(personal);
            }

        }

        //将数据交给业务层
        try {
            deviceService.insertDevice(device, userKey);
            return EasyResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }

    }

    /**
     * 删除一个设备 需要身份验证
     *
     * @param deviceId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deleteDevice/{deviceId}", method = RequestMethod.GET)
    public EasyResult deleteDevice(@PathVariable int deviceId, HttpServletRequest request) {
        String userKey = UserKeyUtil.getUserInfoFromToken(request, jedisClient);
        try {
            deviceService.deleteDevice(deviceId, userKey);
            return EasyResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }

    }

    /**
     * 更新设备 需要做身份验证
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/updateDevice", method = RequestMethod.POST)
    public EasyResult updateDevice(@RequestBody Map map, HttpServletRequest request) {
        String userKey = UserKeyUtil.getUserInfoFromToken(request, jedisClient);
        //获取必要的信息
        Device device = new Device();
        if (map.containsKey("deviceId")) {
            if (CheckNumberUtil.isNumeric(map.get("deviceId").toString()))
                device.setDeviceId(Integer.parseInt(map.get("deviceId").toString()));
        }

        //对设备的描述
        if (map.containsKey("desc")) device.setDeviceDesc(map.get("desc").toString());
        //经纬度
        if (map.containsKey("longitude") && map.containsKey("latitude")) {
            if (CheckNumberUtil.isNumeric(map.get("longitude").toString()))
                device.setDeviceLongitude(map.get("longitude").toString());//经度
            if (CheckNumberUtil.isNumeric(map.get("latitude").toString()))
                device.setDeviceLatitude(map.get("latitude").toString());//纬度
        }
        //状态
        if (map.containsKey("state")) {
            if (CheckNumberUtil.isNumeric(map.get("state").toString())) {
                int state = Integer.parseInt(map.get("state").toString());
                //判断状态是否是允许的状态
                if (state == 1 || state == 0) device.setDeviceState(state);
            }

        }
        //标签

        if (map.containsKey("tag")) device.setDeviceTag(map.get("tag").toString());
        //名字
        if (map.containsKey("name")) {
            device.setDeviceName(map.get("name").toString());
        }
        //隐私
        if (map.containsKey("personal")) {
            device.setDevicePersonal(Integer.parseInt(map.get("personal").toString()));
        }
        //更新
        try {
            deviceService.updateDevice(device, userKey);
            return EasyResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }

    }

    /**
     * 查询用户名下所有公开的设备
     * 包扩再用和停用的
     *
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchUserPublicDevice/{userId}", method = RequestMethod.GET)
    public EasyResult searchUserPublicDevice(@PathVariable int userId) {
        List<Device> list = null;
        try {
            list = deviceService.searchUserPublicDevice(userId);
            return EasyResult.build(200, "success", list);
        } catch (Exception e) {
            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }

    }

    /**
     * 查看用户名下所有的设备 包括私有的 需要做身份验证
     *
     * @param
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchUserAllDevice", method = RequestMethod.GET)
    public EasyResult searchUserAllDevice(HttpServletRequest request) {
        String userKey = UserKeyUtil.getUserInfoFromToken(request, jedisClient);
        List<Device> list = null;
        try {
            list = deviceService.searchUserAllDevice(userKey);
            return EasyResult.build(200, "success", list);

        } catch (Exception e) {
            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }

    }

    /**
     * 查询一台设备的信息 如果是私有设备需要userKey
     *
     * @param request
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchOneDevice/{id}", method = RequestMethod.GET)
    public EasyResult searchOneDevice(HttpServletRequest request, @PathVariable int id) {
        String userKey;
        String devideKey = request.getHeader("api-key");
        if (devideKey != null) {
            try {
                User user = deviceService.getUserByDeviceKey(devideKey);
                userKey = user.getUserKey();
            } catch (Exception e) {
                e.printStackTrace();
                return EasyResult.fail(e.getMessage());
            }
        } else {
            userKey = UserKeyUtil.getUserInfoFromToken(request, jedisClient);
        }
        try {
            Device device = deviceService.searchOneDevice(id, userKey);
            return EasyResult.ok(device);
        } catch (Exception e) {
            e.printStackTrace();
            return EasyResult.fail(e.getMessage());
        }
    }


}
